﻿using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using MyImdb.Common;
using MyImdb.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using System.Windows.Forms;

namespace MyImdb.ViewModel
{
    internal class SettingsViewModel : ViewModelBase
    {
        private ICommand _ChangeDatabaseCommand;
        public ICommand ChangeDatabaseCommand
        {
            get { return _ChangeDatabaseCommand; }
            set
            {
                _ChangeDatabaseCommand = value;
                RaisePropertyChanged("ChangeDatabaseCommand");
            }
        }

        private Settings _AppSettings;
        public Settings AppSettings
        {
            get { return _AppSettings; }
            set
            {
                _AppSettings = value;
                RaisePropertyChanged("AppSettings");
            }
        }

        public SettingsViewModel()
        {
            ChangeDatabaseCommand = new RelayCommand(ChangeSettings);
            ReadSettings();
        }

        private void ReadSettings()
        {
            AppSettings = FileHelper.ReadSettings();
        }

        private void ChangeSettings()
        {
            var dialog = new System.Windows.Forms.FolderBrowserDialog();
            System.Windows.Forms.DialogResult result = dialog.ShowDialog();

            if (result == DialogResult.OK)
            {
                var newPath = dialog.SelectedPath;

                if (!Directory.Exists(newPath))
                {
                    Directory.CreateDirectory(newPath);
                }

                AppSettings.DatabasePath = newPath;
                FileHelper.ModifySettings(JsonConvert.SerializeObject(AppSettings));
            }
        }
    }
}
